package com.beyond.pm.provider

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.datastore.preferences.core.Preferences
import androidx.navigation.compose.rememberNavController
import com.beyond.common.ext.dataStore
import com.beyond.common.local.LocalThemeName
import com.beyond.pm.dp.LanguagePreference
import com.beyond.pm.local.LocalLanguageState
import com.beyond.pm.local.LocalNavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map


fun Preferences.toLanguageSettings(): LanguageSettings {
    return LanguageSettings(
        // languageName
        languageName = LanguagePreference.fromPreferences(this),
    )
}

data class LanguageSettings(
    // languageName
    val languageName: String = LanguagePreference.default,
)

@Composable
fun LanguageSettingsProvider(
    content: @Composable () -> Unit,
) {
    val context = LocalContext.current
    val navController = rememberNavController()
    val settings = remember {
        context.dataStore.data.map { it.toLanguageSettings() }
    }.collectAsState(initial = LanguageSettings(), context = Dispatchers.Default).value
    CompositionLocalProvider(
        // Language
        LocalLanguageState provides settings.languageName,
        LocalNavController provides navController
    ) {
        content()
    }
}